package cn.stylefeng.guns.modular.hx.storage.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.annotation.Resource;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.basic.entity.*;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicPositionGoods;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsResult;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPutDetailed;
import cn.stylefeng.guns.modular.hx.storage.entity.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicPositionGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicPositionGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicPositionGoodsService;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPut;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderPutDetailedResult;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderPutResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderPutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderPutService;
import cn.stylefeng.guns.modular.hx.storage.mapper.HxStoragePutDetailedMapper;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOutDetailedParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutDetailedParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOutDetailedResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutDetailedResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageStockResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOffShelfService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutDetailedService;
import  cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * <p>
 * 入库单明细表 服务实现类
 * </p>
 *
 * @author zhucx
 * @since 2023-08-14
 */
@Service
public class HxStoragePutDetailedServiceImpl extends ServiceImpl<HxStoragePutDetailedMapper, HxStoragePutDetailed> implements HxStoragePutDetailedService {

    @Override
    public void add(HxStoragePutDetailedParam param){
        HxStoragePutDetailed entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HxStoragePutDetailedParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HxStoragePutDetailedParam param){
        HxStoragePutDetailed oldEntity = getOldEntity(param);
        HxStoragePutDetailed newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HxStoragePutDetailedResult findBySpec(HxStoragePutDetailedParam param){
        return null;
    }

    @Override
    public List<HxStoragePutDetailedResult> findListBySpec(HxStoragePutDetailedParam param){
        return this.baseMapper.findListBySpec(param);
    }

    @Override
    public LayuiPageInfo findjiluPageBySpec(HxStoragePutDetailedParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findjiluPageBySpec(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findPageBySpec(HxStoragePutDetailedParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findqualityPageBySpec(HxStoragePutDetailedParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findqualityPageBySpec(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findAppDailingquPageBySpec(HxStoragePutDetailedParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findAppDailingquPageBySpec(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(HxStoragePutDetailedParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HxStoragePutDetailed getOldEntity(HxStoragePutDetailedParam param) {
        return this.getById(getKey(param));
    }

    private HxStoragePutDetailed getEntity(HxStoragePutDetailedParam param) {
        HxStoragePutDetailed entity = new HxStoragePutDetailed();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Resource
    private UserService userService;

	@Resource
    private DeptService deptService;

	@Resource
    private HxStoragePutService hxStoragePutService;
	@Resource
	private HxStoragePutDetailedService hxStoragePutDetailedService;
	@Resource
	private BasicWarehouseService basicWarehouseService;
	@Resource
	private BasicPutgoodsService basicPutgoodsService;

	@Resource
	private HxBasicGoodsService hxBasicGoodsService;



	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

    @Resource
    private BasicTrayService basicTrayService;

    @Resource
    private HxOrderPutService hxOrderPutService;

    @Resource
    private HxOrderPutDetailedService hxOrderPutDetailedService;

    @Resource
    private HxStorageStockService hxStorageStockService;

    @Resource
    private BasicPositionService basicPositionService;

    @Resource
    private BasicCustomerService basicCustomerService;

    @Resource
    private HxBasicPositionGoodsService hxBasicPositionGoodsService;
    
    @Resource
	private BasicXlbOauth2tokenService basicXlbOauth2tokenService;
	
    @Resource
    private HxStorageOffShelfService hxStorageOffShelfService;

    @Resource
    private HxStorageOutDetailedService hxStorageOutDetailedService;

	@Resource
	private BasicAreaService basicAreaService;



	@Override
	@Transactional(rollbackFor = Exception.class,timeout=800000000)
	public void submissionOrder(HxOrderPut hxOrderPut) {
		User user = userService.getcurrentUser();
		String trayCode = getOperateIdOrderPrefix(user)+"-";
		
		//添加入库单
		HxStoragePutParam hxStoragePutParam = new HxStoragePutParam();
		hxStoragePutParam.setCustomerId(hxOrderPut.getCustomerId());
		hxStoragePutParam.setCustomerName(hxOrderPut.getCustomerName());
		hxStoragePutParam.setStorageState("未完成");
		hxStoragePutParam.setYuyueTime(hxOrderPut.getYuyueTime());
		hxStoragePutParam.setStorageNumber(hxOrderPut.getOrderPutNumber());
		hxStoragePutParam.setOrderType(hxOrderPut.getOrderType());
		hxStoragePutParam.setGetWarehouseId(hxOrderPut.getGetWarehouseId());
		hxStoragePutParam.setGetWarehouse(hxOrderPut.getGetWarehouse());
		hxStoragePutParam.setSetUnitId(hxOrderPut.getSetUnitId());
		hxStoragePutParam.setSetUnit(hxOrderPut.getSetUnit());
		hxStoragePutParam.setCreateUserName(user.getName());
		hxStoragePutParam.setNotes(hxOrderPut.getNotes());
		hxStoragePutParam.setDeptId(user.getDeptId());
		hxStoragePutParam.setDeliverId(user.getDeliverId());
		hxStoragePutService.add(hxStoragePutParam);

		//查询商品信息并放入MAP
//		Map<String,HxBasicGoodsResult> goodsMap = new HashMap<>();
		HxBasicGoodsParam q = new HxBasicGoodsParam();
		if(user.getDeptId() != null){
			q.setDeptId(user.getDeptId());
		}
		if(user.getOperateId() != null){
			q.setOperateId(user.getOperateId());
		}
//		List<HxBasicGoodsResult> hxBasicGoods = hxBasicGoodsService.findListBySpec(q);
//		for(HxBasicGoodsResult obj : hxBasicGoods){
//			goodsMap.put(obj.getId().toString(),obj);
//		}

		//查询订单明细
		BigDecimal as = new BigDecimal(0);
		HxOrderPutDetailedParam hxOrderPutDetailedParam = new HxOrderPutDetailedParam();
		hxOrderPutDetailedParam.setOrderPutNumber(hxOrderPut.getOrderPutNumber());
		List<HxOrderPutDetailedResult> putDlist = hxOrderPutDetailedService.totalListByGandPSpec(hxOrderPutDetailedParam);//入库订单明细
		for (HxOrderPutDetailedResult putD : putDlist) {
			Long positionId = null;
			String positionNumber = null;
			boolean position = false;
			HxBasicGoods hxBasicGoods = hxBasicGoodsService.getById(putD.getGoodsId());
			if(hxOrderPut.getOrderType().equals("门店退货")) {
				HxBasicPositionGoodsParam check = new HxBasicPositionGoodsParam();
				check.setWarehouseId(hxOrderPut.getGetWarehouseId());
				check.setPositionType("拣货位");
				check.setGoodsId(putD.getGoodsId());
				HxBasicPositionGoodsResult goodsResult = hxBasicPositionGoodsService.findBySpec(check);
				if(goodsResult != null) {
					positionId = goodsResult.getPositionId();
					positionNumber = goodsResult.getPositionNumber();
					position = true;
				}
			} else {
				/**  2024-09-06 15:30 需求修改
				 * 推荐拣货位
				 * 1、高架无库存，拣货位低于安全库存，直接推荐一托入拣货位
				 * 2、新品【无库存且未拣过货】，按照拆零和整件推荐一托到空的拣货位
				 * 3、无库存但是拣货明细中有记录，优化按照最新一次拣货对应区域推荐一托入空拣货位，无空货位则不推荐
				 */
				BasicCustomer basicCustomer = basicCustomerService.getById(hxBasicGoods.getGoodsCustomerId());//客户
				BasicCustomer r = basicCustomerService.getById(basicCustomer.getId());
				if(ToolUtil.isNotEmpty(r.getInWarehousing())&&r.getInWarehousing().equals("1")) {
					//判断有无同品不同单据 已被推荐
					HxStoragePutDetailedParam findyituijianp = new HxStoragePutDetailedParam();
					findyituijianp.setStorageNumber(putD.getOrderPutNumber());
					findyituijianp.setGoodsId(putD.getGoodsId());
					Integer yitj = this.findyituijianDetailed(findyituijianp);
					if(yitj == 0) {
						// 查询高架是否有库存
						List<HxStorageStock> stockList = hxStorageStockService.lambdaQuery()
								.eq(HxStorageStock::getGoodsId, putD.getGoodsId())
								.eq(HxStorageStock::getWarehouseId, hxOrderPut.getGetWarehouseId())
								.eq(HxStorageStock::getStockState, "正常")
								.list();
						Map<String,BigDecimal> stockPositionTypeMap = new HashMap<>();
						Map<String,BasicPositionParam> goodsPositionMap = new HashMap<>();
						for(HxStorageStock obj : stockList){
							if("拣货位".equals(obj.getPositionType())){
								goodsPositionMap.put(obj.getGoodsId().toString(),BasicPositionParam.builder()
										.id(obj.getPositionId().intValue())
										.positionNumber(obj.getPositionNumber())
										.build());
							}
							if(stockPositionTypeMap.get(obj.getPositionType()) == null){
								stockPositionTypeMap.put(obj.getPositionType(),obj.getJibenNum());
							}else{
								stockPositionTypeMap.put(obj.getPositionType(),stockPositionTypeMap.get(obj.getPositionType()).add(obj.getJibenNum()));
							}
						}
						//高架位没有库存
						if(stockPositionTypeMap.get("存储位") == null || stockPositionTypeMap.get("存储位").compareTo(new BigDecimal(0)) < 1){
							if(hxBasicGoods != null && ToolUtil.isNotEmpty(hxBasicGoods.getAnquanNum())){
								BigDecimal anquanNumJbdw = new BigDecimal(hxBasicGoods.getAnquanNum()).multiply(new BigDecimal(hxBasicGoods.getKcRate()));
								// 拣货位无库存
								if(stockPositionTypeMap.get("拣货位") == null){
									HxBasicPositionGoods one = this.hxBasicPositionGoodsService.lambdaQuery()
											.eq(HxBasicPositionGoods::getGoodsId, putD.getGoodsId())
											.eq(HxBasicPositionGoods::getWarehouseId,hxOrderPut.getGetWarehouseId())
											.one();
									if(one != null){
										positionId = one.getPositionId();
										positionNumber = one.getPositionNumber();
										position = true;
									}else{
										HxStorageOutDetailed storageOutDetailed = this.hxStorageOutDetailedService.lambdaQuery()
												.eq(HxStorageOutDetailed::getGoodsId, putD.getGoodsId())
												.orderByDesc(HxStorageOutDetailed::getId)
												.last("limit 1")
												.one();
										//2、新品【无库存且未拣过货】，按照拆零和整件推荐一托到空的拣货位
										if(storageOutDetailed == null){
											//查询空库位
											BasicPositionResult basicPositionResult = this.basicPositionService.findKongBySpec(BasicPositionParam.builder()
													.warehouseId(hxOrderPut.getGetWarehouseId().intValue())
													.dismantlingParts(hxBasicGoods.getDismantlingParts())
													.positionType("拣货位")
													.build());
											if(basicPositionResult != null){
												positionId = Long.valueOf(basicPositionResult.getId());
												positionNumber = basicPositionResult.getPositionNumber();
												position = true;
											}
										}else{
											//3、无库存但是拣货明细中有记录，优化按照最新一次拣货对应区域推荐一托入空拣货位，无空货位则按照拆零和整件推荐所有托到空的拣货位
											//库位信息
											BasicPosition basicPosition = this.basicPositionService.getById(storageOutDetailed.getPositionId());
											//查询空库位
											BasicPositionResult basicPositionResult = this.basicPositionService.findKongBySpec(BasicPositionParam.builder()
													.warehouseId(hxOrderPut.getGetWarehouseId().intValue())
													.positionType("拣货位")
													.dismantlingParts(hxBasicGoods.getDismantlingParts())
													.positionAreaId(basicPosition.getPositionAreaId())
													.build());
											if(basicPositionResult != null){
												positionId = Long.valueOf(basicPositionResult.getId());
												positionNumber = basicPositionResult.getPositionNumber();
												position = true;
											}
											
										}
									}
									
									
								}else if(anquanNumJbdw.compareTo(stockPositionTypeMap.get("拣货位")) == 1){
									//1、高架无库存，拣货位低于安全库存，直接推荐一托入拣货位
									positionId = Long.valueOf(goodsPositionMap.get(putD.getGoodsId().toString()).getId());
									positionNumber = goodsPositionMap.get(putD.getGoodsId().toString()).getPositionNumber();
									position = true;
								}
							}
						}
					}
				}

			}
			
			BigDecimal detailedPutnum = new BigDecimal(putD.getSumNum());//入库数量
			BigDecimal Supportvolume = new BigDecimal(putD.getGoodsSupportvolume());//每托存量
			BigDecimal w = new BigDecimal(putD.getGoodsWeight());//重量
			BigDecimal v = new BigDecimal(putD.getGoodsVolume());//体积
			BigDecimal u = new BigDecimal(putD.getGoodsPrice());//单价
			int zz = 1;
			
			if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1) {//判断一托是否可以装下全部
				HxStoragePutDetailedParam s = new HxStoragePutDetailedParam();
				create(s,putD);
				s.setPutWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				s.setPutVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
				s.setPutMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				s.setStorageNumber(hxOrderPut.getOrderPutNumber());
				if (position) {
					s.setPositionId(positionId);
					s.setPositionNumber(positionNumber);
//					position = false;
				}
				s.setNum(putD.getSumNum());
				s.setJibenNum(new BigDecimal(putD.getSumNum()).multiply(new BigDecimal(putD.getRate())).toString());

				s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);//项目编码+五位随机数
				zz++;
				this.add(s);//添加入库单明细
			} else {
				List<HxStoragePutDetailedParam> sList = new ArrayList<HxStoragePutDetailedParam>();
				HxStoragePutDetailedParam s = new HxStoragePutDetailedParam();
				while (detailedPutnum.compareTo(as)==1) {
					if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1||detailedPutnum.subtract(Supportvolume).compareTo(as)== 0) {
						create(s,putD);
						//剩余刚好一托 够装下
						s.setPutWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setStorageNumber(hxOrderPut.getOrderPutNumber());
						if (position) {
							s.setPositionId(positionId);
							s.setPositionNumber(positionNumber);
//							position = false;
						}
						s.setNum(detailedPutnum.toString());
						s.setJibenNum(new BigDecimal(detailedPutnum.toString()).multiply(new BigDecimal(putD.getRate())).toString());

						s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);//项目编码+五位随机数
						zz++;
						detailedPutnum = new BigDecimal(0);
					} else {
						create(s,putD);
						//整托
						s.setPutWeight(w.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutVolume(v.multiply(Supportvolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutMoney(u.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setStorageNumber(hxOrderPut.getOrderPutNumber());
						if (position) {
							s.setPositionId(positionId);
							s.setPositionNumber(positionNumber);
//							position = false;
						}
						s.setNum(Supportvolume.toString());
						s.setJibenNum(new BigDecimal(Supportvolume.toString()).multiply(new BigDecimal(putD.getRate())).toString());

						s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);//项目编码+五位随机数
						zz++;
						BigDecimal detailedPutnum2	=  detailedPutnum.subtract(Supportvolume);
						detailedPutnum = detailedPutnum2;
					}
					sList.add(s);
					s = new HxStoragePutDetailedParam();
				}
				if (sList.size()>0) {
					//批量保存入库单名 ，托盘
                    this.saveBatchList(sList);
				}
			}
		}
		//更新入库单
		HxOrderPutParam orderPutParam = new HxOrderPutParam();
		orderPutParam.setId(hxOrderPut.getId());
		orderPutParam.setYuyueTime(hxOrderPut.getYuyueTime());
		orderPutParam.setSubmitTime(new Date());//提交时间
		orderPutParam.setSubmitUserName(user.getName());//提交人名称
		orderPutParam.setOrderState("收货中");
		hxOrderPutService.update(orderPutParam);
	}

	private void create(HxStoragePutDetailedParam s, HxOrderPutDetailedResult putD) {
		s.setPutState("待质检");
		s.setGoodsId(putD.getGoodsId());
		s.setGoodsName(putD.getGoodsName());
		s.setGoodsNumber(putD.getGoodsNumber());
		s.setGoodsPcode69(putD.getGoodsPcode69());
		s.setGoodsSpecs(putD.getGoodsSpecs());
		s.setUnit(putD.getUnit());
		s.setJibenUnit(putD.getJibenUnit());

		s.setRate(putD.getRate());
		s.setDismantlingParts(putD.getDismantlingParts());
		
		s.setGoodsWeight(putD.getGoodsWeight());
		s.setGoodsVolume(putD.getGoodsVolume());
		s.setGoodsPrice(putD.getGoodsPrice());
		s.setDetailedDate(putD.getDetailedDate());
		s.setPrintNum("0");
	}

	@Override
	public boolean saveBatchList(List<HxStoragePutDetailedParam> list) {
		return this.baseMapper.saveBatchList(list);
	}

	@Override
	public HxStoragePutDetailedResult details(HxStoragePutDetailedParam param) {
		return this.baseMapper.details(param);
	}

	@Override
	public List<HxStoragePutDetailedResult> restfinddetailedSumlist(HxStoragePutDetailedParam param) {
		List<HxStoragePutDetailedResult> hxStoragePutDetailedResults = this.baseMapper.restfinddetailedSumlist(param);
		return hxStoragePutDetailedResults;
	}

	@Override
	public HxStoragePutDetailedResult restfinddetailedSum(HxStoragePutDetailedParam param) {
		return this.baseMapper.restfinddetailedSum(param);
	}

	@Override
	public List<HxStoragePutDetailedResult> restfinddetailedSumDetailedlist(HxStoragePutDetailedParam param) {
		return this.baseMapper.restfinddetailedSumDetailedlist(param);
	}

	@Override
	public void allqualityupdateBySpec(HxStoragePutDetailedParam param) {
		this.baseMapper.allqualityupdateBySpec(param);
	}

	@Override
	public HxStoragePutDetailedResult findCheckBySpec(HxStoragePutDetailedParam check) {
		return this.baseMapper.findCheckBySpec(check);
	}

	@Override
	public void deleteBySpec(HxStoragePutDetailedParam param) {
		this.baseMapper.deleteBySpec(param);
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData editGoods(User user, HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		QueryWrapper<HxStoragePut> queryWrapper = new QueryWrapper<HxStoragePut>();
		queryWrapper.eq("storage_number", hxStoragePutDetailedParam.getStorageNumber());
		HxStoragePut hxStoragePut = hxStoragePutService.getOne(queryWrapper);
		
    	HxStoragePutDetailedParam check = new HxStoragePutDetailedParam();
    	check.setStorageNumber(hxStoragePutDetailedParam.getStorageNumber());
    	check.setGoodsId(hxStoragePutDetailedParam.getGoodsId());
    	check.setPutState("待质检");
    	HxStoragePutDetailedResult detailedResult = this.findCheckBySpec(check);
    	if(detailedResult != null) {
            return ResponseData.error("已开始质检，无法修改");
    	}
    	
		BigDecimal goodsBottom = new BigDecimal(hxStoragePutDetailedParam.getGoodsBottom());//底
		BigDecimal goodsLamination = new BigDecimal(hxStoragePutDetailedParam.getGoodsLamination());//叠层
		BigDecimal goodsSupportvolume = goodsBottom.multiply(goodsLamination);//每托存量
    	HxBasicGoodsParam basicGoodsParam = new HxBasicGoodsParam();//更新商品
    	basicGoodsParam.setId(Integer.parseInt(hxStoragePutDetailedParam.getGoodsId().toString()));
    	basicGoodsParam.setGoodsBottom(hxStoragePutDetailedParam.getGoodsBottom());
    	basicGoodsParam.setGoodsLamination(hxStoragePutDetailedParam.getGoodsLamination());
    	basicGoodsParam.setGoodsSupportvolume(goodsSupportvolume.toString());
    	basicGoodsParam.setGoodsVolume(hxStoragePutDetailedParam.getGoodsVolume());
		basicGoodsParam.setGoodsWeight(hxStoragePutDetailedParam.getGoodsWeight());
    	hxBasicGoodsService.update(basicGoodsParam);
    	
    	HxStoragePutDetailedParam deleteparam = new HxStoragePutDetailedParam();//删除待入库托盘
    	deleteparam.setStorageNumber(hxStoragePutDetailedParam.getStorageNumber());
    	deleteparam.setGoodsId(hxStoragePutDetailedParam.getGoodsId());
    	this.deleteBySpec(deleteparam);
    	
    	HxBasicGoods hxBasicGoods = hxBasicGoodsService.getById(hxStoragePutDetailedParam.getGoodsId());//商品
    	
    	HxOrderPutDetailedParam hxOrderPutDetailedParam = new HxOrderPutDetailedParam();
    	hxOrderPutDetailedParam.setOrderPutNumber(hxStoragePutDetailedParam.getStorageNumber());
    	hxOrderPutDetailedParam.setGoodsId(hxStoragePutDetailedParam.getGoodsId());
    	List<HxOrderPutDetailedResult> odlist = hxOrderPutDetailedService.findListBySpec(hxOrderPutDetailedParam);//入库订单明细
    	for (HxOrderPutDetailedResult r : odlist) {
			BigDecimal sumNum = new BigDecimal(r.getSumNum());
			BigDecimal goodsVolume = new BigDecimal(hxStoragePutDetailedParam.getGoodsVolume());
			BigDecimal goodsWeight = new BigDecimal(hxStoragePutDetailedParam.getGoodsWeight());
			BigDecimal rate = new BigDecimal(r.getRate());
			BigDecimal cgRate = new BigDecimal(hxBasicGoods.getCgRate());
			if(rate.compareTo(cgRate) == -1) {
				//如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
				BigDecimal div = cgRate.divide(rate,3, BigDecimal.ROUND_HALF_DOWN);
				BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
				goodsVolume = divv_v;
				BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
				goodsWeight = divv_w;
				BigDecimal divv_s = goodsSupportvolume.multiply(div);
				goodsSupportvolume = divv_s;
			}
			if(rate.compareTo(cgRate) == 1) {
				//如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
				BigDecimal div = rate.divide(cgRate,3, BigDecimal.ROUND_HALF_DOWN);
				BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
				goodsVolume = divv_v;
				BigDecimal divv_s = goodsSupportvolume.divide(div);
				goodsSupportvolume = divv_s;
				BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				goodsWeight = divv_w;
			}
			HxOrderPutDetailedParam updateHxOrderPutDetailedParam = new HxOrderPutDetailedParam();
			updateHxOrderPutDetailedParam.setId(r.getId());
			updateHxOrderPutDetailedParam.setGoodsVolume(goodsVolume.toString());
			updateHxOrderPutDetailedParam.setPutVolume(sumNum.multiply(goodsVolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
			updateHxOrderPutDetailedParam.setGoodsWeight(goodsWeight.toString());
			updateHxOrderPutDetailedParam.setPutWeight(sumNum.multiply(goodsWeight).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());

			updateHxOrderPutDetailedParam.setGoodsSupportvolume(goodsSupportvolume.toString());
			hxOrderPutDetailedService.update(updateHxOrderPutDetailedParam);
		}

		//托盘信息
		String trayCode = getOperateIdOrderPrefix(user)+"-";
		
		//查询订单明细
		BigDecimal as = new BigDecimal("0");
		HxOrderPutDetailedParam totalhxOrderPutDetailedParam = new HxOrderPutDetailedParam();
		totalhxOrderPutDetailedParam.setOrderPutNumber(hxStoragePutDetailedParam.getStorageNumber());
		totalhxOrderPutDetailedParam.setGoodsId(hxStoragePutDetailedParam.getGoodsId());
		List<HxOrderPutDetailedResult> putDlist = hxOrderPutDetailedService.totalListByGandPSpec(hxOrderPutDetailedParam);//入库订单明细
		for (HxOrderPutDetailedResult putD : putDlist) {
			Long positionId = null;
			String positionNumber = null;
			boolean position = false;
			/**  2024-09-06 15:30 需求修改
			 * 推荐拣货位
			 * 1、高架无库存，拣货位低于安全库存，直接推荐一托入拣货位
			 * 2、新品【无库存且未拣过货】，按照拆零和整件推荐一托到空的拣货位
			 * 3、无库存但是拣货明细中有记录，优化按照最新一次拣货对应区域推荐一托入空拣货位，无空货位则不推荐
			 */
			BasicCustomer basicCustomer = basicCustomerService.getById(hxBasicGoods.getGoodsCustomerId());//客户
			BasicCustomer r = basicCustomerService.getById(basicCustomer.getId());
			if(ToolUtil.isNotEmpty(r.getInWarehousing())&&r.getInWarehousing().equals("1")) {
				//判断有无同品不同单据 已被推荐
				HxStoragePutDetailedParam findyituijianp = new HxStoragePutDetailedParam();
				findyituijianp.setStorageNumber(putD.getOrderPutNumber());
				findyituijianp.setGoodsId(putD.getGoodsId());
				Integer yitj = this.findyituijianDetailed(findyituijianp);
				if(yitj == 0) {
					// 查询高架是否有库存
					List<HxStorageStock> stockList = hxStorageStockService.lambdaQuery()
							.eq(HxStorageStock::getGoodsId, putD.getGoodsId())
							.eq(HxStorageStock::getWarehouseId, hxStoragePut.getGetWarehouseId())
							.eq(HxStorageStock::getStockState, "正常")
							.list();
					Map<String,BigDecimal> stockPositionTypeMap = new HashMap<>();
					Map<String,BasicPositionParam> goodsPositionMap = new HashMap<>();
					for(HxStorageStock obj : stockList){
						if("拣货位".equals(obj.getPositionType())){
							goodsPositionMap.put(obj.getGoodsId().toString(),BasicPositionParam.builder()
									.id(obj.getPositionId().intValue())
									.positionNumber(obj.getPositionNumber())
									.build());
						}
						if(stockPositionTypeMap.get(obj.getPositionType()) == null){
							stockPositionTypeMap.put(obj.getPositionType(),obj.getJibenNum());
						}else{
							stockPositionTypeMap.put(obj.getPositionType(),stockPositionTypeMap.get(obj.getPositionType()).add(obj.getJibenNum()));
						}
					}
					//高架位没有库存
					if(stockPositionTypeMap.get("存储位") == null || stockPositionTypeMap.get("存储位").compareTo(new BigDecimal(0)) < 1){
						if(ToolUtil.isNotEmpty(hxBasicGoods.getAnquanNum())){
							BigDecimal anquanNumJbdw = new BigDecimal(hxBasicGoods.getAnquanNum()).multiply(new BigDecimal(hxBasicGoods.getKcRate()));
							// 拣货位无库存
							if(stockPositionTypeMap.get("拣货位") == null){
								HxBasicPositionGoods one = this.hxBasicPositionGoodsService.lambdaQuery()
										.eq(HxBasicPositionGoods::getGoodsId, putD.getGoodsId())
										.eq(HxBasicPositionGoods::getWarehouseId,hxStoragePut.getGetWarehouseId())
										.one();
								if(one != null){
									positionId = one.getPositionId();
									positionNumber = one.getPositionNumber();
									position = true;
								}else{
									//查询是否有拣货明细
									HxStorageOutDetailed storageOutDetailed = this.hxStorageOutDetailedService.lambdaQuery()
											.eq(HxStorageOutDetailed::getGoodsId, putD.getGoodsId())
											.orderByDesc(HxStorageOutDetailed::getId)
											.last("limit 1")
											.one();
									//2、新品【无库存且未拣过货】，按照拆零和整件推荐一托到空的拣货位
									if(storageOutDetailed == null){
										//查询空库位
										BasicPositionResult basicPositionResult = this.basicPositionService.findKongBySpec(BasicPositionParam.builder()
												.warehouseId(hxStoragePut.getGetWarehouseId().intValue())
												.dismantlingParts(hxBasicGoods.getDismantlingParts())
												.positionType("拣货位")
												.build());
										if(basicPositionResult != null){
											positionId = Long.valueOf(basicPositionResult.getId());
											positionNumber = basicPositionResult.getPositionNumber();
											position = true;
										}
									}else{
										//3、无库存但是拣货明细中有记录，优化按照最新一次拣货对应区域推荐一托入空拣货位，无空货位则不推荐
										//库位信息
										BasicPosition basicPosition = this.basicPositionService.getById(storageOutDetailed.getPositionId());
										//查询空库位
										BasicPositionResult basicPositionResult = this.basicPositionService.findKongBySpec(BasicPositionParam.builder()
												.warehouseId(hxStoragePut.getGetWarehouseId().intValue())
												.positionType("拣货位")
												.dismantlingParts(hxBasicGoods.getDismantlingParts())
												.positionAreaId(basicPosition.getPositionAreaId())
												.build());
										if(basicPositionResult != null){
											positionId = Long.valueOf(basicPositionResult.getId());
											positionNumber = basicPositionResult.getPositionNumber();
											position = true;
										}
									}
								}
							}else if(anquanNumJbdw.compareTo(stockPositionTypeMap.get("拣货位")) == 1){
								//1、高架无库存，拣货位低于安全库存，直接推荐一托入拣货位
								positionId = Long.valueOf(goodsPositionMap.get(putD.getGoodsId().toString()).getId());
								positionNumber = goodsPositionMap.get(putD.getGoodsId().toString()).getPositionNumber();
								position = true;
							}
						}
					}
				}
			}
			
			BigDecimal detailedPutnum = new BigDecimal(putD.getSumNum());//入库数量
			BigDecimal Supportvolume = new BigDecimal(putD.getGoodsSupportvolume());//每托存量
			BigDecimal w = new BigDecimal(putD.getGoodsWeight());//重量
			BigDecimal v = new BigDecimal(putD.getGoodsVolume());//体积
			BigDecimal u = new BigDecimal(putD.getGoodsPrice());//单价
			int zz = 1;
			
			if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1) {//判断一托是否可以装下全部
				HxStoragePutDetailedParam s = new HxStoragePutDetailedParam();
				create(s,putD);
				s.setPutWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				s.setPutVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
				s.setPutMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				s.setStorageNumber(hxStoragePutDetailedParam.getStorageNumber());
				if (position) {
					s.setPositionId(positionId);
					s.setPositionNumber(positionNumber);
//					position = false;
				}
				s.setNum(putD.getSumNum());

				BigDecimal jibenNum = new BigDecimal(putD.getSumNum()).multiply(new BigDecimal(putD.getRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				s.setJibenNum(jibenNum.toString());
				s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);
				zz++;
				this.add(s);//添加入库单明细
			} else {
				List<HxStoragePutDetailedParam> sList = new ArrayList<HxStoragePutDetailedParam>();
				HxStoragePutDetailedParam s = new HxStoragePutDetailedParam();
				while (detailedPutnum.compareTo(as)==1) {
					if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1||detailedPutnum.subtract(Supportvolume).compareTo(as)== 0) {
						create(s,putD);
						//剩余刚好一托 够装下
						s.setPutWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setStorageNumber(hxStoragePutDetailedParam.getStorageNumber());
						if (position) {
							s.setPositionId(positionId);
							s.setPositionNumber(positionNumber);
//							position = false;
						}
						s.setNum(detailedPutnum.toString());
						BigDecimal jibenNum = new BigDecimal(detailedPutnum.toString()).multiply(new BigDecimal(putD.getRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
						s.setJibenNum(jibenNum.toString());
						s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);
						zz++;
						detailedPutnum = new BigDecimal(0);
					} else {
						create(s,putD);
						//整托
						s.setPutWeight(w.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutVolume(v.multiply(Supportvolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setPutMoney(u.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						s.setStorageNumber(hxStoragePutDetailedParam.getStorageNumber());
						if (position) {
							s.setPositionId(positionId);
							s.setPositionNumber(positionNumber);
//							position = false;
						}
						s.setNum(Supportvolume.toString());
						BigDecimal jibenNum = new BigDecimal(Supportvolume.toString()).multiply(new BigDecimal(putD.getRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
						s.setJibenNum(jibenNum.toString());
						s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);
						zz++;
						BigDecimal detailedPutnum2	=  detailedPutnum.subtract(Supportvolume);
						detailedPutnum = detailedPutnum2;
					}
					sList.add(s);
					s = new HxStoragePutDetailedParam();
				}
				if (sList.size()>0) {
					//批量保存入库单名 ，托盘
                    this.saveBatchList(sList);
				}
			}
		}
		return ResponseData.success();
	}

	@Override
	public List<HxStoragePutDetailedResult> appfindlistyilingqu(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		return this.baseMapper.appfindlistyilingqu(hxStoragePutDetailedParam);
	}

	@Override
	public List<HxStorageStockResult> storageStocklist(HxStorageStockParam hxStorageStockParam) {
		return this.baseMapper.storageStocklist(hxStorageStockParam);
	}

	@Override
	public HxStoragePutDetailedResult appPutfindBySpec(HxStoragePutDetailedParam param) {
		return this.baseMapper.appPutfindBySpec(param);
	}


//	public static void main(String[] args) {
//		BigDecimal bd =  new BigDecimal("15");
//		BigDecimal bd2 = new BigDecimal("13");
//		System.out.println(bd.divide(bd2 ,3, RoundingMode.HALF_UP));
//	}
@Override
@Transactional(rollbackFor = Exception.class,timeout=80000)
public ResponseData put(User user, HxStoragePutDetailed detailed,HxStoragePutDetailedParam hxStoragePutDetailedParam) {

	HxStoragePutParam hxStoragePutParam = new HxStoragePutParam();
	hxStoragePutParam.setStorageNumber(detailed.getStorageNumber());
	HxStoragePutResult hxStoragePutResult = hxStoragePutService.findBySpec(hxStoragePutParam);//入库单

	BasicPositionParam basicPositionParam = new BasicPositionParam();//判断库位是否存在
	basicPositionParam.setPositionState("1");
	basicPositionParam.setWarehouseId(Integer.parseInt(hxStoragePutResult.getGetWarehouseId().toString()));
	basicPositionParam.setPositionNumber(hxStoragePutDetailedParam.getPositionNumber());
	BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, null, null);
	if(basicPositionResult == null) {
		return ResponseData.error(hxStoragePutResult.getGetWarehouse()+"中"+hxStoragePutDetailedParam.getPositionNumber()+"库位系统不存在或禁用");
	}

//	if(basicPositionResult.getPositionType().equals("存储位")){
//		Integer count = hxStorageStockService.lambdaQuery()
//				.eq(HxStorageStock::getPositionNumber, hxStoragePutDetailedParam.getPositionNumber())
//				.eq(HxStorageStock::getOperateId, user.getOperateId())
//				.count();
//		if(count>0) {
//			return ResponseData.error("库位存在多个库存");
//		}
//	}
	//查看库位的绑定关系，如果已绑定且不为该商品提示
//	HxBasicPositionGoodsParam q = new HxBasicPositionGoodsParam();
//	q.setPositionId(basicPositionResult.getId().longValue());
//	List<HxBasicPositionGoodsResult> positionLists = hxBasicPositionGoodsService.findListBySpec(q);
//	if(positionLists !=null && positionLists.size() > 0){
//		boolean flag = false;
//		for(HxBasicPositionGoodsResult obj : positionLists){
//			if(obj.getGoodsId().equals(detailed.getGoodsId())){
//				flag = true;
//			}
//		}
//		if(!flag){
//			return ResponseData.error(hxStoragePutDetailedParam.getPositionNumber()+"库位未绑定该商品");
//		}
//	}

	HxBasicGoods hxBasicGoods = hxBasicGoodsService.getById(detailed.getGoodsId());//商品
	try{
		//入库上架加个校验：如果商品是拆零，然后要入的库位是拣货位，但是该库位所在的库区是整箱区的话，就提示失败
		BasicArea basicArea = basicAreaService.getById(basicPositionResult.getPositionAreaId());
		if("是".equals(hxBasicGoods.getDismantlingParts()) && "拣货位".equals(basicPositionResult.getPositionType())){
			if(basicArea != null && "否".equals(basicArea.getDismantlingParts())){
				return ResponseData.error("拆零商品不能上架非拆零区的拣货位");
			}
		}
		if("否".equals(hxBasicGoods.getDismantlingParts()) && "拣货位".equals(basicPositionResult.getPositionType())){
			if(basicArea != null && "是".equals(basicArea.getDismantlingParts())){
				return ResponseData.error("整箱商品不能上架拆零区的拣货位");
			}
		}
		//如果入到整箱区，判断不能一位多品
		if(basicArea != null && "否".equals(basicArea.getDismantlingParts())&& "拣货位".equals(basicPositionResult.getPositionType())){
			Integer count = hxBasicPositionGoodsService.lambdaQuery()
					.ne(HxBasicPositionGoods::getGoodsId, detailed.getGoodsId())
					.eq(HxBasicPositionGoods::getPositionId, basicPositionResult.getId())
					.count();
			if(count>0) {
				return ResponseData.error("库位已绑定其他商品");
			}
		}
	}catch (Exception e){
		e.printStackTrace();
	}
	BasicCustomer basicCustomer = basicCustomerService.getById(hxBasicGoods.getGoodsCustomerId());//客户
//	BasicCustomer r = basicCustomerService.getById(hxBasicGoods.getGoodsCustomerId());//客户

	//如果是拣选位，并且开启必须绑定拣选位限制，则提示
	if("是".equals(basicCustomer.getShelfPickPositionFlag())){
		if(!"拣货位".equals(basicPositionResult.getPositionType())){
			Integer count = this.hxBasicPositionGoodsService.lambdaQuery()
					.eq(HxBasicPositionGoods::getGoodsId, detailed.getGoodsId())
//					.eq(HxBasicPositionGoods::getPositionId, basicPositionResult.getId())
					.count();
			if(count < 1){
				return ResponseData.success("上架品未绑定库位，无法操作！");
			}
		}

	}

	HxOrderPutParam hxOrderPutParam = new HxOrderPutParam();
	hxOrderPutParam.setOrderPutNumber(detailed.getStorageNumber());
	HxOrderPutResult hxOrderPutResult = hxOrderPutService.findBySpec(hxOrderPutParam);//入库订单

	HxStorageStock addStockParam = new HxStorageStock();//添加库存
	if (ToolUtil.isNotEmpty(basicCustomer.getModeTms())) {
		if (basicCustomer.getModeTms().equals("1")) {
			addStockParam.setStockState("正常");
		} else if (basicCustomer.getModeTms().equals("3")) {
			addStockParam.setStockState("待回传");
		} else {
			addStockParam.setStockState("正常");
		}
	} else {
		addStockParam.setStockState("正常");
	}

	addStockParam.setOperateId(Long.parseLong(basicCustomer.getCustomerOperateId().toString()));
	addStockParam.setOperateName(basicCustomer.getCustomerOperateName());
	addStockParam.setCustomerId(hxStoragePutResult.getCustomerId());
	addStockParam.setCustomerName(hxStoragePutResult.getCustomerName());
	addStockParam.setWarehouseId(hxStoragePutResult.getGetWarehouseId());
	addStockParam.setWarehouseName(hxStoragePutResult.getGetWarehouse());
	addStockParam.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
	addStockParam.setAreaName(basicPositionResult.getPositionAreaName());
	addStockParam.setAreaNumber(basicPositionResult.getAreaNumber());
	addStockParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
	addStockParam.setPositionNumber(hxStoragePutDetailedParam.getPositionNumber());
	addStockParam.setPositionType(basicPositionResult.getPositionType());
	addStockParam.setTrayNumber(detailed.getTrayNumber());

	addStockParam.setGoodsId(detailed.getGoodsId());
	addStockParam.setGoodsName(detailed.getGoodsName());
	addStockParam.setGoodsNumber(detailed.getGoodsNumber());
	addStockParam.setGoodsPcode69(detailed.getGoodsPcode69());
	addStockParam.setGoodsSpecs(detailed.getGoodsSpecs());
	addStockParam.setGoodsBigtypeId(hxBasicGoods.getGoodsBigtypedictId());
	addStockParam.setGoodsBigtype(hxBasicGoods.getGoodsBigtype());

	addStockParam.setJibenUnit(hxBasicGoods.getJibenUnit());
	addStockParam.setKcUnit(hxBasicGoods.getKcUnit());
	addStockParam.setKcRate(hxBasicGoods.getKcRate());
	addStockParam.setCgUnit(hxBasicGoods.getCgUnit());
	addStockParam.setCgRate(hxBasicGoods.getCgRate());
	addStockParam.setPfUnit(hxBasicGoods.getPfUnit());
	addStockParam.setPfRate(hxBasicGoods.getPfRate());
	addStockParam.setPsUnit(hxBasicGoods.getPsUnit());
	addStockParam.setPsRate(hxBasicGoods.getPsRate());
	addStockParam.setDetailedDate(detailed.getDetailedDate());
	addStockParam.setGoodsWarranty(hxBasicGoods.getGoodsWarranty());
	addStockParam.setPutDate(DateUtil.getDate());

	addStockParam.setStockVolume(detailed.getPutVolume());
	addStockParam.setStockWeight(detailed.getPutWeight());
	addStockParam.setStockMoney(detailed.getPutMoney());

	addStockParam.setSetUnitId(hxStoragePutResult.getSetUnitId());
	addStockParam.setSetUnit(hxStoragePutResult.getSetUnit());
	addStockParam.setDeptId(user.getDeptId());
	addStockParam.setDeliverId(user.getDeliverId());

	BigDecimal as = new BigDecimal("0");
	BigDecimal num = new BigDecimal(detailed.getNum());
	BigDecimal realNum = new BigDecimal(detailed.getRealNum());
	BigDecimal goodsVolume = new BigDecimal(detailed.getGoodsVolume());
	BigDecimal goodsWeight = new BigDecimal(detailed.getGoodsWeight());
	BigDecimal goodsPrice = new BigDecimal(detailed.getGoodsPrice());
	BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoods.getGoodsChargingCg());
	BigDecimal kcRate = new BigDecimal(hxBasicGoods.getKcRate());
	BigDecimal rate = new BigDecimal(detailed.getRate());
	goodsPrice = kcRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);//换算率*基本单位单价=库存单位单价
	if(kcRate.compareTo(rate) == -1) {
		//如果库存换算率 小于 换算率：  库存体积  =  体积/（换算率/库存换算率）
		BigDecimal div = rate.divide(kcRate,3, BigDecimal.ROUND_HALF_DOWN);
		BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
		goodsVolume = divv_v;
		BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
		goodsWeight = divv_w;
		BigDecimal divv_n = realNum.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
		realNum = divv_n;
	}
	if(kcRate.compareTo(rate) == 1) {
		//如果库存换算率 大于 换算率：  库存体积  =  体积*（库存换算率/换算率）
		BigDecimal div = kcRate.divide(rate,3, BigDecimal.ROUND_HALF_DOWN);
		BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
		goodsVolume = divv_v;
		BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
		goodsWeight = divv_w;
		BigDecimal divv_n = realNum.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
		realNum = divv_n;
	}
	//addStockParam.setKcNum(realNum.toString());
	//基本数量
	//库存数量*库存换算率=基本数量
	BigDecimal jibenNum = new BigDecimal(hxStoragePutDetailedParam.getJibenRealNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
	addStockParam.setJibenNum(jibenNum);
	//基本数量除以库存换算率=库存数量
	BigDecimal kcnums = jibenNum.divide(kcRate, 3, BigDecimal.ROUND_HALF_DOWN);
	addStockParam.setKcNum(kcnums.toString());

	addStockParam.setGoodsVolume(goodsVolume.toString());
	addStockParam.setGoodsWeight(goodsWeight.toString());
	addStockParam.setGoodsPrice(goodsPrice.toString());
	addStockParam.setTransferTime(new Date());
	if(realNum.compareTo(num) != 0) {
		if(realNum.compareTo(as) == 1) {
			addStockParam.setStockVolume(goodsVolume.multiply(realNum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
			addStockParam.setStockWeight(goodsWeight.multiply(realNum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			addStockParam.setStockMoney(goodsPrice.multiply(realNum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
		}
	}
	if(realNum.compareTo(as) == 1) {
		hxStorageStockService.save(addStockParam);
	}

	//更新入库单明细
	hxStoragePutDetailedParam.setPutState("已上架");
	hxStoragePutDetailedParam.setStockId(Long.parseLong(addStockParam.getId().toString()));
	hxStoragePutDetailedParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
	hxStoragePutDetailedParam.setPositionNumber(basicPositionResult.getPositionNumber());
	hxStoragePutDetailedParam.setPutUserName(user.getName());
	hxStoragePutDetailedParam.setPutTime(new Date());
	hxStoragePutDetailedParam.setXlbPositionId(basicPositionResult.getPositionXlbId());

	this.update(hxStoragePutDetailedParam);

	//更新库位商品绑定关系
	if(realNum.compareTo(as) == 1) {
		if(ToolUtil.isNotEmpty(basicPositionResult.getPositionType())) {
			if(basicPositionResult.getPositionType().equals("拣货位")) {
				HxBasicPositionGoodsParam check = new HxBasicPositionGoodsParam();
				check.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
				check.setGoodsId(detailed.getGoodsId());
				HxBasicPositionGoodsResult goodsResult = hxBasicPositionGoodsService.findBySpec(check);
				if(goodsResult == null) {
					HxBasicPositionGoodsParam add = new HxBasicPositionGoodsParam();
					add.setWarehouseId(Long.parseLong(basicPositionResult.getWarehouseId().toString()));
					add.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
					add.setAreaName(basicPositionResult.getPositionAreaName());
					add.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
					add.setPositionNumber(basicPositionResult.getPositionNumber());
					add.setPositionPickingorder(basicPositionResult.getPositionPickingorder());
					add.setGoodsId(detailed.getGoodsId());
					add.setGoodsName(hxBasicGoods.getGoodsName());
					add.setGoodsNumber(hxBasicGoods.getGoodsNumber());
					add.setGoodsPcode69(hxBasicGoods.getGoodsPcode69());
					add.setGoodsSpecs(hxBasicGoods.getGoodsSpecs());
					add.setAnquanNum(hxBasicGoods.getAnquanNum());
					add.setPsUnit(hxBasicGoods.getPsUnit());
					add.setPsRate(hxBasicGoods.getPsRate());
					add.setJibenUnit(hxBasicGoods.getJibenUnit());
					add.setOperator(user.getName());
					this.hxBasicPositionGoodsService.add(add);
				}
			}
		}
	}

	//校验入库单是否完成
	QueryWrapper<HxStoragePutDetailed> queryWrapper = new QueryWrapper<HxStoragePutDetailed>();
	queryWrapper.eq("storage_number", detailed.getStorageNumber());
	queryWrapper.ne("put_state", "已上架");
	int ns = this.count(queryWrapper);
	if(ns == 0) {
		hxOrderPutParam.setId(hxOrderPutResult.getId());
		hxOrderPutParam.setOrderState("已完成");
		hxOrderPutParam.setCompleteTime(new Date());
		hxOrderPutService.update(hxOrderPutParam);

		hxStoragePutParam.setId(hxStoragePutResult.getId());
		hxStoragePutParam.setStorageState("已完成");
		hxStoragePutParam.setCompleteTime(new Date());
		hxStoragePutService.update(hxStoragePutParam);
		
		List <HxStoragePutDetailed> lists = hxStoragePutDetailedService.lambdaQuery()
				.eq(HxStoragePutDetailed::getStorageNumber, hxStoragePutResult.getStorageNumber())
				.orderByAsc(HxStoragePutDetailed::getGoodsId)
				.orderByDesc(HxStoragePutDetailed::getRealNum)
				.list();

		// 在入库完成之后，将入库单信息通过调用新增入库单接口，将入库单来回传给新零帮
		BasicWarehouse w = basicWarehouseService.getById(hxStoragePutResult.getGetWarehouseId());

		if(ToolUtil.isNotEmpty(basicCustomer.getGsnumber())&&ToolUtil.isNotEmpty(basicCustomer.getStoreIdXlb())) {
			if(ToolUtil.isNotEmpty(basicCustomer.getModeTms())&&basicCustomer.getModeTms().equals("3")) {
		        if(ToolUtil.isNotEmpty(basicCustomer.getXlbStorehouseId())) {
					BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
							.eq(BasicPutgoods::getId, hxOrderPutResult.getSetUnitId())
							.last("LIMIT 1")
							.one();
					//在入库完成之后，将入库单信息通过调用新增入库单接口，将入库单来回传给新零帮
					//String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.inorder.save";
					String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.inorder.save";

					JSONArray ordersArray = new JSONArray();
					Long zpgoodsid = null;
					Map<Long, BigDecimal> remainingZpnumMap = new HashMap<>(); // 记录剩余的赠品数量
					for (HxStoragePutDetailed hxStoragePutDetailed:lists){
                    	if(!hxStoragePutDetailed.getPutState().equals("已上架")) {
                    		continue;
                    	}
						if(zpgoodsid == null){
							zpgoodsid = hxStoragePutDetailed.getGoodsId();
						} else {
							if(!zpgoodsid.equals(hxStoragePutDetailed.getGoodsId())){
								zpgoodsid = hxStoragePutDetailed.getGoodsId();
							}
						}
						JSONObject orderObject = new JSONObject();

						HxBasicGoods goods = hxBasicGoodsService.lambdaQuery()
								.eq(HxBasicGoods::getId, hxStoragePutDetailed.getGoodsId())
								.last("LIMIT 1").one();

						HxOrderPutDetailed order = hxOrderPutDetailedService.lambdaQuery()
								.eq(HxOrderPutDetailed::getOrderPutNumber, hxOrderPutResult.getOrderPutNumber())
								.eq(HxOrderPutDetailed::getGoodsId, hxStoragePutDetailed.getGoodsId())
								.last("LIMIT 1")
								.one();

						if (goods != null && order != null && ToolUtil.isNotEmpty(order.getZpNum())) {
							// 获取该商品的赠品数量信息
							BigDecimal zpnum = new BigDecimal(order.getZpNum());
							BigDecimal realQuantity = new BigDecimal(hxStoragePutDetailed.getRealNum());
							if (!remainingZpnumMap.containsKey(hxStoragePutDetailed.getGoodsId())) {
								remainingZpnumMap.put(hxStoragePutDetailed.getGoodsId(), zpnum);
							}
							BigDecimal remainingZpnum = remainingZpnumMap.getOrDefault(hxStoragePutDetailed.getGoodsId(), BigDecimal.ZERO);

							if (remainingZpnum.compareTo(BigDecimal.ZERO) != 0 ) {
								// 在数量大于赠品数量的明细中添加赠品数量
								BigDecimal zpRate = new BigDecimal(order.getZpRate());
								BigDecimal zpnum_real = remainingZpnum.multiply(zpRate).setScale(3, BigDecimal.ROUND_HALF_DOWN);
								BigDecimal realnum = new BigDecimal(hxStoragePutDetailed.getRealNum());
								BigDecimal result = realnum.subtract(remainingZpnum);

								BigDecimal jibenrate = new BigDecimal(order.getRate());
								if (realQuantity.compareTo(remainingZpnum)>=0){
									orderObject.put("present_quantity", remainingZpnum); // 赠品数量 必填
									orderObject.put("basic_present_quantity", zpnum_real); // 赠品基本数量 必填
									orderObject.put("quantity", result);//数量 必填
									orderObject.put("basic_quantity",result.multiply(jibenrate) );//基本数量 必填
									remainingZpnumMap.put(hxStoragePutDetailed.getGoodsId(), BigDecimal.ZERO); // 重置剩余赠品数量
								}else if (realQuantity.compareTo(remainingZpnum)<0){
									orderObject.put("present_quantity", realQuantity); // 赠品数量 必填
									BigDecimal  basic_present_quantity = realQuantity.multiply(zpRate).setScale(3, BigDecimal.ROUND_HALF_DOWN);
									orderObject.put("basic_present_quantity", basic_present_quantity); // 赠品基本数量 必填
									orderObject.put("quantity", BigDecimal.ZERO);//数量 必填
									orderObject.put("basic_quantity",BigDecimal.ZERO);//基本数量 必填
									remainingZpnumMap.put(hxStoragePutDetailed.getGoodsId(), remainingZpnum.subtract(realQuantity)); // 更新剩余赠品数量
								}

							} else {
								BigDecimal realnum = new BigDecimal(hxStoragePutDetailed.getRealNum());
								BigDecimal jibenrate = new BigDecimal(order.getRate());

								orderObject.put("present_quantity", BigDecimal.ZERO); // 其他托的赠品数量为0
								orderObject.put("basic_present_quantity", BigDecimal.ZERO); // 其他托的赠品基本数量为0
								orderObject.put("quantity", realnum);//数量 必填
								orderObject.put("basic_quantity",realnum.multiply(jibenrate) );//基本数量 必填

							}
						} else {
							BigDecimal realnum = new BigDecimal(hxStoragePutDetailed.getRealNum());
							BigDecimal jibenrate = new BigDecimal(order.getRate());

							orderObject.put("present_quantity", BigDecimal.ZERO); // 没有赠品数量的情况下赠品数量为0
							orderObject.put("basic_present_quantity", BigDecimal.ZERO); // 没有赠品数量的情况下赠品基本数量为0
							orderObject.put("quantity", realnum);//数量 必填
							orderObject.put("basic_quantity",realnum.multiply(jibenrate) );//基本数量 必填

						}
						// 创建订单对象


						orderObject.put("basic_unit",order.getUnit());//基本单位 必填

						LocalDate productionDate = LocalDate.parse(hxStoragePutDetailed.getDetailedDate());
						// 保质期（以月份表示）
						String shelfLifeMonths =goods.getGoodsWarranty();
						LocalDateTime outputDateTime = productionDate.atStartOfDay();

						// 计算到期日期
						LocalDate expiryDate = productionDate.plusMonths(Integer.parseInt(shelfLifeMonths));
						// 格式化输出到期日期
						DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
						LocalDateTime expiryDateTime = expiryDate.atStartOfDay();

						String formattedExpiryDate = expiryDateTime.format(formatter);// 格式化输出到期日期
						String deliveryDate = outputDateTime.format(formatter);// 格式化输出生产日期
						orderObject.put("expire_date", formattedExpiryDate);//	到期日期
						orderObject.put("item_code", hxStoragePutDetailed.getGoodsNumber());//商品条码
						orderObject.put("item_bar_code", goods.getGoodsPcode69());
						orderObject.put("item_id",goods.getGoodsXlbId());//商品id 必填
						orderObject.put("item_name",hxStoragePutDetailed.getGoodsName() );//商品名称 必填
						orderObject.put("item_spec",hxStoragePutDetailed.getGoodsSpecs() );//规格
						orderObject.put("memo","" );//备注
						orderObject.put("present_ratio",order.getZpRate());//	赠品换算率 必填
						orderObject.put("present_unit",order.getZpUnit());//	赠品单位 必填
						orderObject.put("producing_date",deliveryDate);//生产日期
						orderObject.put("ratio", hxStoragePutDetailed.getRate());//换算率 必填
						orderObject.put("storage_id",hxStoragePutDetailed.getXlbPositionId());//库位id
						orderObject.put("storage_name",hxStoragePutDetailed.getPositionNumber());//库位名称
						orderObject.put("unit", hxStoragePutDetailed.getUnit());//单位 必填
						ordersArray.put(orderObject);
					}
					JSONObject json = new JSONObject();
					json.put("adjust_reason_name", "");//调整原因
					json.put("client_id",basicPutgoods.getXlbClientId());// 发货客户id
					json.put("client_name", basicPutgoods.getPutgoodsName());//发货客户名称
					json.put("details", ordersArray);//明细
					json.put("memo","" );//备注
					json.put("order_fid",hxOrderPutResult.getOrderPutNumber());
					json.put("wms_fid", hxOrderPutResult.getOrderPutNumber());
					if (hxOrderPutResult.getOrderType().equals("门店调入")){
						json.put("order_type","STORE_IN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
					}
					if (hxOrderPutResult.getOrderType().equals("采购收货")){
						json.put("order_type","RECEIVE" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
					}
					if (hxOrderPutResult.getOrderType().equals("批发退货")){
						json.put("order_type","WHOLESALE_RETURN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
					}
					if (hxOrderPutResult.getOrderType().equals("调整入库")){
						json.put("order_type","ADJUST_IN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
					}
					if (hxOrderPutResult.getOrderType().equals("甩货入库")){
						json.put("order_type","DUMP_IN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
					}
					if (hxOrderPutResult.getOrderType().equals("仓间调拨")){
						json.put("order_type","TRANSFER" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
					}
					json.put("store_id",basicCustomer.getStoreIdXlb());
					json.put("storehouse_id", w.getWarehouseXlbId());
					//System.out.println(json.toString());

					BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
					oauth2tokenParam.setDeliverId(basicCustomer.getDeliverId());
					oauth2tokenParam.setGsnumber(basicCustomer.getGsnumber());
					BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

					String response = HttpRequest.post(url)
							.timeout(60000)
							.header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
							.body(json.toString()).execute().body();
					//System.out.println("================json："+json+"========================");
					//System.out.println("================post："+response+"========================");
					JSONObject jsonObject = new JSONObject(response);

					if (jsonObject.get("code").toString().equals("0")) {
						hxOrderPutService.lambdaUpdate()
								.set(HxOrderPut::getReturnStatus,"已完成")
								.eq(HxOrderPut::getOrderPutNumber,hxOrderPutResult.getOrderPutNumber())
								.update();

						for (HxStoragePutDetailed hxStoragePutDetailed:lists){
							if(hxStoragePutDetailed.getPutState().equals("已上架")) {
								hxStorageStockService.lambdaUpdate()
								.eq(HxStorageStock::getId, hxStoragePutDetailed.getStockId())
								.set(HxStorageStock::getStockState, "正常")
								.update();
							}
						}
						//System.out.println(jsonObject.toString());
						Object data = jsonObject.get("data");
						return ResponseData.success("回传成功");
					} else {
						//System.out.println(jsonObject.toString());
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
						return ResponseData.error("回传失败");
					}
				}
			}
		}
	}
	return ResponseData.success();
}








	@Override
	public HxStorageStockResult findBySpec1(HxStorageStockParam param) {
		return this.baseMapper.findBySpec1(param);
	}

	@Override
	public void updatePrint(HxStoragePutDetailedParam param) {
		this.baseMapper.updatePrint(param);
	}

	@Override
	public LayuiPageInfo  findwarehousingstat(HxStoragePutDetailedParam hxStoragePutDetailedParam, String condition) {
		Page pageContext = getPageContext();
		IPage printwarehousingstat = this.baseMapper.getPrintwarehousingstat(pageContext,condition,hxStoragePutDetailedParam);
		return LayuiPageFactory.createPageInfo(printwarehousingstat);
	}

	@Override
	public List<HxStoragePutDetailedResult> findShangjiaData(HxStoragePutDetailedResult hxStoragePutDetailedResult) {
		return this.baseMapper.findShangjiaData(hxStoragePutDetailedResult);
	}

	@Override
	public List <HxStoragePutDetailedResult> findStoragePutDetailsList(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
	return this.baseMapper.findStoragePutList(hxStoragePutDetailedParam);
	}

	@Override
	public List <HxStoragePutDetailedResult> findlistAllBySpec(HxStoragePutDetailedParam hxStoragePutDetailedParam, String condition, Long operateId) {
		List<HxStoragePutDetailedResult> arrlist = this.baseMapper.findlistAllBySpec(hxStoragePutDetailedParam,condition,operateId);
		return arrlist;
	}

	@Override
	public HxStoragePutDetailedResult count(HxStoragePutDetailedParam hxStoragePutDetailedParam, String condition, Long operateId) {
		return this.baseMapper.count(hxStoragePutDetailedParam,condition,operateId);
	}
	@Override
	public HxStoragePutDetailedResult count1(HxStoragePutDetailedParam hxStoragePutDetailedParam, String condition, Long operateId) {
		return this.baseMapper.count1(hxStoragePutDetailedParam,condition,operateId);
	}

	@Override
	public List <HxStoragePutDetailedResult> listAll1(HxStoragePutDetailedParam hxStoragePutDetailedParam, String condition, Long operateId) {
		List<HxStoragePutDetailedResult> arrlist = this.baseMapper.listAll1(hxStoragePutDetailedParam,condition,operateId);
		return arrlist;
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=800000000)
	public ResponseData return_put(User user, HxStoragePutDetailed detailed,
								   HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		HxStoragePutParam hxStoragePutParam = new HxStoragePutParam();
		hxStoragePutParam.setStorageNumber(detailed.getStorageNumber());
		HxStoragePutResult hxStoragePutResult = hxStoragePutService.findBySpec(hxStoragePutParam);//入库单

		BasicPositionParam basicPositionParam = new BasicPositionParam();//判断库位是否存在
		basicPositionParam.setPositionState("1");
		basicPositionParam.setWarehouseId(Integer.parseInt(hxStoragePutResult.getGetWarehouseId().toString()));
		basicPositionParam.setPositionNumber(hxStoragePutDetailedParam.getPositionNumber());
		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(), user.getOperateId());
		if(basicPositionResult == null) {
			return ResponseData.error(hxStoragePutResult.getGetWarehouse()+"中"+hxStoragePutDetailedParam.getPositionNumber()+"库位系统不存在");
		}

		HxBasicGoods hxBasicGoods = hxBasicGoodsService.getById(detailed.getGoodsId());//商品


		BasicCustomer basicCustomer = basicCustomerService.getById(hxBasicGoods.getGoodsCustomerId());//客户

		HxOrderPutParam hxOrderPutParam = new HxOrderPutParam();
		hxOrderPutParam.setOrderPutNumber(detailed.getStorageNumber());
		HxOrderPutResult hxOrderPutResult = hxOrderPutService.findBySpec(hxOrderPutParam);//入库订单

		HxStorageStockParam addStockParam = new HxStorageStockParam();//添加库存
		addStockParam.setStockState("正常");
		addStockParam.setOperateId(Long.parseLong(basicCustomer.getCustomerOperateId().toString()));
		addStockParam.setOperateName(basicCustomer.getCustomerOperateName());
		addStockParam.setCustomerId(hxStoragePutResult.getCustomerId());
		addStockParam.setCustomerName(hxStoragePutResult.getCustomerName());
		addStockParam.setWarehouseId(hxStoragePutResult.getGetWarehouseId());
		addStockParam.setWarehouseName(hxStoragePutResult.getGetWarehouse());
		addStockParam.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
		addStockParam.setAreaName(basicPositionResult.getPositionAreaName());
		addStockParam.setAreaNumber(basicPositionResult.getAreaNumber());
		addStockParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
		addStockParam.setPositionNumber(hxStoragePutDetailedParam.getPositionNumber());
		addStockParam.setPositionType(basicPositionResult.getPositionType());
		addStockParam.setTrayNumber(detailed.getTrayNumber());

		addStockParam.setGoodsId(detailed.getGoodsId());
		addStockParam.setGoodsName(detailed.getGoodsName());
		addStockParam.setGoodsNumber(detailed.getGoodsNumber());
		addStockParam.setGoodsPcode69(detailed.getGoodsPcode69());
		addStockParam.setGoodsSpecs(detailed.getGoodsSpecs());
		addStockParam.setGoodsBigtypeId(hxBasicGoods.getGoodsBigtypedictId());
		addStockParam.setGoodsBigtype(hxBasicGoods.getGoodsBigtype());

		addStockParam.setStockVolume(detailed.getPutVolume());
		addStockParam.setStockWeight(detailed.getPutWeight());
		addStockParam.setStockMoney(detailed.getPutMoney());

		addStockParam.setJibenUnit(hxBasicGoods.getJibenUnit());
		addStockParam.setKcUnit(hxBasicGoods.getKcUnit());
		addStockParam.setKcRate(hxBasicGoods.getKcRate());
		addStockParam.setCgUnit(hxBasicGoods.getCgUnit());
		addStockParam.setCgRate(hxBasicGoods.getCgRate());
		addStockParam.setPfUnit(hxBasicGoods.getPfUnit());
		addStockParam.setPfRate(hxBasicGoods.getPfRate());
		addStockParam.setPsUnit(hxBasicGoods.getPsUnit());
		addStockParam.setPsRate(hxBasicGoods.getPsRate());
		addStockParam.setDetailedDate(hxStoragePutDetailedParam.getDetailedDate());
		addStockParam.setGoodsWarranty(hxBasicGoods.getGoodsWarranty());
		addStockParam.setPutDate(DateUtil.getDate());

		addStockParam.setSetUnitId(hxStoragePutResult.getSetUnitId());
		addStockParam.setSetUnit(hxStoragePutResult.getSetUnit());
		addStockParam.setDeptId(user.getDeptId());
		addStockParam.setDeliverId(user.getDeliverId());

		BigDecimal as = new BigDecimal("0");
		BigDecimal num = new BigDecimal(detailed.getNum());
		BigDecimal realNum = new BigDecimal(hxStoragePutDetailedParam.getRealNum());
		BigDecimal goodsVolume = new BigDecimal(detailed.getGoodsVolume());
		BigDecimal goodsWeight = new BigDecimal(detailed.getGoodsWeight());
		BigDecimal goodsPrice = new BigDecimal(detailed.getGoodsPrice());
		BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoods.getGoodsChargingCg());
		BigDecimal kcRate = new BigDecimal(hxBasicGoods.getKcRate());
		BigDecimal rate = new BigDecimal(detailed.getRate());

		if (realNum.compareTo(BigDecimal.ZERO) > 0){
			if (hxStoragePutDetailedParam.getApproveUnit() == null || hxStoragePutDetailedParam.getApproveUnit()== "") {
				return ResponseData.error("归位单位不能为空");
			}
			if (hxStoragePutDetailedParam.getDetailedDate() == null || hxStoragePutDetailedParam.getDetailedDate()== "") {
				return ResponseData.error("生产日期不能为空");
			}
			if(hxStoragePutDetailedParam.getApproveUnit().equals(hxBasicGoods.getCgUnit())) {
				BigDecimal cgRates = new BigDecimal(hxBasicGoods.getCgRate());
				BigDecimal divide = realNum.multiply(cgRates).setScale(3, BigDecimal.ROUND_HALF_DOWN);

				addStockParam.setJibenNum(divide);
				BigDecimal kcnums = divide.divide(kcRate, 3, BigDecimal.ROUND_HALF_DOWN);
				addStockParam.setKcNum(kcnums.toString());
			}else if(hxStoragePutDetailedParam.getApproveUnit().equals(hxBasicGoods.getKcUnit())) {

				BigDecimal divide = realNum.multiply(kcRate).setScale(3, BigDecimal.ROUND_HALF_DOWN);

				addStockParam.setJibenNum(divide);
				BigDecimal kcnums = divide.divide(kcRate, 3, BigDecimal.ROUND_HALF_DOWN);
				addStockParam.setKcNum(kcnums.toString());
			}else if(hxStoragePutDetailedParam.getApproveUnit().equals(hxBasicGoods.getPfUnit())) {
				BigDecimal pfRates = new BigDecimal(hxBasicGoods.getPfRate());
				BigDecimal divide = realNum.multiply(pfRates).setScale(3, BigDecimal.ROUND_HALF_DOWN);

				addStockParam.setJibenNum(divide);
				BigDecimal kcnums = divide.divide(kcRate, 3, BigDecimal.ROUND_HALF_DOWN);
				addStockParam.setKcNum(kcnums.toString());
			}else if(hxStoragePutDetailedParam.getApproveUnit().equals(hxBasicGoods.getPsUnit())) {
				BigDecimal psRates = new BigDecimal(hxBasicGoods.getPsRate());
				BigDecimal divide = realNum.multiply(psRates).setScale(3, BigDecimal.ROUND_HALF_DOWN);

				addStockParam.setJibenNum(divide);
				BigDecimal kcnums = divide.divide(kcRate, 3, BigDecimal.ROUND_HALF_DOWN);
				addStockParam.setKcNum(kcnums.toString());
			}else if(hxStoragePutDetailedParam.getApproveUnit().equals(hxBasicGoods.getJibenUnit())) {

				addStockParam.setJibenNum(realNum);
				BigDecimal kcnums = realNum.divide(kcRate, 3, BigDecimal.ROUND_HALF_DOWN);
				addStockParam.setKcNum(kcnums.toString());
			}else {
				return ResponseData.error("归位单位不正确");
			}
		}

		goodsPrice = kcRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);//换算率*基本单位单价=库存单位单价
		if(kcRate.compareTo(rate) == -1) {
			//如果库存换算率 小于 换算率：  库存体积  =  体积/（换算率/库存换算率）
			BigDecimal div = rate.divide(kcRate,3, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
			goodsVolume = divv_v;
			BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
			goodsWeight = divv_w;
			BigDecimal divv_n = realNum.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			realNum = divv_n;
		}
		if(kcRate.compareTo(rate) == 1) {
			//如果库存换算率 大于 换算率：  库存体积  =  体积*（库存换算率/换算率）
			BigDecimal div = kcRate.divide(rate,3, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
			goodsVolume = divv_v;
			BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			goodsWeight = divv_w;
			BigDecimal divv_n = realNum.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
			realNum = divv_n;
		}
		//addStockParam.setKcNum(realNum.toString());
		//addStockParam.setJibenNum(new BigDecimal(realNum.toString()).multiply(new BigDecimal(hxBasicGoods.getKcRate())));



//		BigDecimal volumes = goodsVolume.divide(new BigDecimal(hxBasicGoods.getCgRate()), 4, BigDecimal.ROUND_HALF_DOWN);
//		BigDecimal goodsVolume1 = volumes.multiply(jibenNum);
//		addStockParam.setGoodsVolume(goodsVolume1.toString());

		addStockParam.setGoodsVolume(goodsVolume.toString());
		addStockParam.setGoodsWeight(goodsWeight.toString());
		addStockParam.setGoodsPrice(goodsPrice.toString());
		addStockParam.setTransferTime(new Date());
		if(num.compareTo(realNum) != 0) {
			if(realNum.compareTo(as) == 1) {
				addStockParam.setStockVolume(goodsVolume.multiply(realNum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
				addStockParam.setStockWeight(goodsWeight.multiply(realNum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				addStockParam.setStockMoney(goodsPrice.multiply(realNum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			}
		}
		if(realNum.compareTo(as) == 1) {
			hxStorageStockService.add(addStockParam);
		}

		//更新入库单明细
		hxStoragePutDetailedParam.setPutState("已上架");
		hxStoragePutDetailedParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
		hxStoragePutDetailedParam.setPositionNumber(basicPositionResult.getPositionNumber());
		hxStoragePutDetailedParam.setPutUserName(user.getName());
		hxStoragePutDetailedParam.setPutTime(new Date());

		this.update(hxStoragePutDetailedParam);

		//更新库位商品绑定关系
		if(realNum.compareTo(as) == 1) {
			if(ToolUtil.isNotEmpty(basicPositionResult.getPositionType())) {
				if(basicPositionResult.getPositionType().equals("拣货位")) {
					HxBasicPositionGoodsParam check = new HxBasicPositionGoodsParam();
					check.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
					check.setGoodsId(detailed.getGoodsId());
					HxBasicPositionGoodsResult goodsResult = hxBasicPositionGoodsService.findBySpec(check);
					if(goodsResult == null) {
						HxBasicPositionGoodsParam add = new HxBasicPositionGoodsParam();
						add.setWarehouseId(Long.parseLong(basicPositionResult.getWarehouseId().toString()));
						add.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
						add.setAreaName(basicPositionResult.getPositionAreaName());
						add.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
						add.setPositionNumber(basicPositionResult.getPositionNumber());
						add.setPositionPickingorder(basicPositionResult.getPositionPickingorder());
						add.setGoodsId(detailed.getGoodsId());
						add.setGoodsName(hxBasicGoods.getGoodsName());
						add.setGoodsNumber(hxBasicGoods.getGoodsNumber());
						add.setGoodsPcode69(hxBasicGoods.getGoodsPcode69());
						add.setGoodsSpecs(hxBasicGoods.getGoodsSpecs());
						add.setAnquanNum(hxBasicGoods.getAnquanNum());
						add.setPsUnit(hxBasicGoods.getPsUnit());
						add.setPsRate(hxBasicGoods.getPsRate());
						add.setJibenUnit(hxBasicGoods.getJibenUnit());
						this.hxBasicPositionGoodsService.add(add);
					}
				}
			}
		}

		//校验入库单是否完成
		QueryWrapper<HxStoragePutDetailed> queryWrapper = new QueryWrapper<HxStoragePutDetailed>();
		queryWrapper.eq("storage_number", detailed.getStorageNumber());
		queryWrapper.ne("put_state", "已上架");
		int ns = this.count(queryWrapper);
		if(ns == 0) {
			hxOrderPutParam.setId(hxOrderPutResult.getId());
			hxOrderPutParam.setOrderState("已完成");
			hxOrderPutParam.setCompleteTime(new Date());
			hxOrderPutService.update(hxOrderPutParam);

			hxStoragePutParam.setId(hxStoragePutResult.getId());
			hxStoragePutParam.setStorageState("已完成");
			hxStoragePutParam.setCompleteTime(new Date());
			hxStoragePutService.update(hxStoragePutParam);

			BasicWarehouse w = basicWarehouseService.getById(hxStoragePutResult.getGetWarehouseId());
			BasicCustomer r = basicCustomerService.getById(basicCustomer.getId());
			// 在退货单入库完成之后，将退货单信息通过调用新增入库归位单接口，将退货单来回传给新零帮
			// 如果是新零帮，则需要调用接口，将退货单信息回传给新零帮，如果是其他门店，则不需要调用接口，直接将退货单信息回传给门店管理员
    		if(ToolUtil.isNotEmpty(r.getGsnumber())&&ToolUtil.isNotEmpty(r.getStoreIdXlb())) {
				if(ToolUtil.isNotEmpty(r.getModeTms())&&r.getModeTms().equals("3")) {
		          	if(r.getXlbStorehouseId()!=null){
						  //String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.returnstorage.save";
				          String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.returnstorage.save";
						  List <HxStoragePutDetailed> lists = hxStoragePutDetailedService.lambdaQuery()
								  .eq(HxStoragePutDetailed::getStorageNumber, hxStoragePutResult.getStorageNumber())
								  .list();
						  JSONArray ordersArray = new JSONArray();

						  for (HxStoragePutDetailed hxStoragePutDetailed:lists) {
							  HxBasicGoods goods = hxBasicGoodsService.lambdaQuery()
									  .eq(HxBasicGoods::getId, hxStoragePutDetailed.getGoodsId())
									  .one();

							  HxOrderPutDetailed order = hxOrderPutDetailedService.lambdaQuery()
									  .eq(HxOrderPutDetailed::getOrderPutNumber, hxOrderPutResult.getOrderPutNumber())
									  .eq(HxOrderPutDetailed::getGoodsId, hxStoragePutDetailed.getGoodsId())
									  .one();

							  JSONObject orderObject = new JSONObject();
							  BigDecimal realNums = new BigDecimal(hxStoragePutDetailed.getRealNum());
							//  BigDecimal jibenrate = new BigDecimal(order.getRate());
							  orderObject.put("basic_unit", goods.getJibenUnit());//基本单位 必填



							  if (realNums.compareTo(BigDecimal.ZERO) > 0) {

								  orderObject.put("approve_unit", hxStoragePutDetailed.getApproveUnit());//归位单位

								  LocalDate productionDate = LocalDate.parse(hxStoragePutDetailed.getDetailedDate());
								  // 保质期（以月份表示）
								  String shelfLifeMonths = goods.getGoodsWarranty();

								  // 计算到期日期
								  LocalDate expiryDate = productionDate.plusMonths(Integer.parseInt(shelfLifeMonths));

								  // 格式化输出到期日期
								  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
								  String formattedExpiryDate = expiryDate.format(formatter);

								  orderObject.put("expire_date", formattedExpiryDate);//	到期日期
								  orderObject.put("basic_present_quantity", 0);//赠品基本数量
								  if (hxStoragePutDetailed.getApproveUnit().equals(goods.getCgUnit())) {
									  BigDecimal cgRates = new BigDecimal(goods.getCgRate());
									  BigDecimal divide = realNums.multiply(cgRates).divide(cgRates, 3, BigDecimal.ROUND_HALF_DOWN);

									  orderObject.put("approve_quantity", divide);//归位数量
									  orderObject.put("approve_ratio", goods.getCgRate());//归位换算率
									  orderObject.put("basic_quantity", realNums.multiply(cgRates));//基本数量
									  orderObject.put("quantity", realNums);//数量 必填
									  orderObject.put("ratio", goods.getCgRate());//换算率 必填
									  orderObject.put("unit", goods.getCgUnit());//单位 必填

								  } else if (hxStoragePutDetailed.getApproveUnit().equals(goods.getKcUnit())) {

									  BigDecimal kcRates = new BigDecimal(goods.getKcRate());
									  BigDecimal divide = realNums.multiply(kcRates).divide(kcRates, 3, BigDecimal.ROUND_HALF_DOWN);
									  orderObject.put("approve_quantity", divide);//归位数量
									  orderObject.put("approve_ratio", goods.getKcRate());//归位换算率
									  orderObject.put("basic_quantity", realNums.multiply(kcRates));//基本数量
									  orderObject.put("quantity", realNums);//数量 必填
									  orderObject.put("ratio", goods.getKcRate());//换算率 必填
									  orderObject.put("unit", goods.getKcUnit());//单位 必填

								  } else if (hxStoragePutDetailed.getApproveUnit().equals(goods.getPfUnit())) {
									  BigDecimal pfRates = new BigDecimal(goods.getPfRate());
									  BigDecimal divide = realNums.multiply(pfRates).divide(pfRates, 3, BigDecimal.ROUND_HALF_DOWN);
									  orderObject.put("approve_quantity", divide);//归位数量
									  orderObject.put("approve_ratio", goods.getPfRate());//归位换算率
									  orderObject.put("basic_quantity", realNums.multiply(pfRates));//基本数量
									  orderObject.put("quantity", realNums);//数量 必填
									  orderObject.put("ratio", goods.getPfRate());//换算率 必填
									  orderObject.put("unit", goods.getPfUnit());//单位 必填
								  } else if (hxStoragePutDetailed.getApproveUnit().equals(goods.getPsUnit())) {
									  BigDecimal psRates = new BigDecimal(goods.getPsRate());
									  BigDecimal divide = realNums.multiply(psRates).divide(psRates, 3, BigDecimal.ROUND_HALF_DOWN);
									  orderObject.put("approve_quantity", divide);//归位数量
									  orderObject.put("approve_ratio", goods.getPsRate());//归位换算率
									  orderObject.put("basic_quantity", realNums.multiply(psRates));//基本数量
									  orderObject.put("quantity", realNums);//数量 必填
									  orderObject.put("ratio", goods.getPsRate());//换算率 必填
									  orderObject.put("unit", goods.getPsUnit());//单位 必填
								  } else if (hxStoragePutDetailed.getApproveUnit().equals(goods.getJibenUnit())) {
									  // BigDecimal divide = jibennum.multiply(jibenrate);
									  orderObject.put("approve_quantity", realNums);//归位数量
									  orderObject.put("approve_ratio", 1);//归位换算率
									  orderObject.put("basic_quantity", realNums);//基本数量
									  orderObject.put("quantity", realNums);//数量 必填
									  orderObject.put("ratio", 1);//换算率 必填
									  orderObject.put("unit", goods.getJibenUnit());//单位 必填
								  } else {
									  return ResponseData.error("归位单位不正确");
								  }
							  }
							  if (realNums.compareTo(BigDecimal.ZERO) == 0) {
								  orderObject.put("approve_unit", goods.getJibenUnit());//归位单位


								  orderObject.put("expire_date", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));							  orderObject.put("basic_present_quantity", 0);//赠品基本数量


								  orderObject.put("approve_quantity", 0);//归位数量
								  orderObject.put("approve_ratio", 1);//归位换算率
								  orderObject.put("basic_quantity", 0);//基本数量
								  orderObject.put("quantity", 0);//数量 必填
								  orderObject.put("ratio", 1);//换算率 必填
								  orderObject.put("unit", hxStoragePutDetailed.getApproveUnit());//单位 必填
							  }
							  orderObject.put("item_code", hxStoragePutDetailed.getGoodsNumber());//商品条码
							  orderObject.put("item_bar_code", goods.getGoodsPcode69());//商品代码 必填
							  orderObject.put("item_id", goods.getGoodsXlbId());//商品id 必填
							  orderObject.put("item_name", hxStoragePutDetailed.getGoodsName());//商品名称 必填
							  orderObject.put("item_spec", hxStoragePutDetailed.getGoodsSpecs());//规格
							  orderObject.put("memo", "");//备注
							  orderObject.put("producing_date", hxStoragePutDetailed.getDetailedDate());//生产日期

//						BasicPosition basicPosition = basicPositionService.lambdaQuery()
//								.eq(BasicPosition::getPositionNumber, hxStoragePutDetailedParam.getPositionNumber())
//								.one();
							  BasicPosition basicPosition = basicPositionService.lambdaQuery()
									  .select(BasicPosition::getPositionXlbId) // 只查询 xlbid 字段
									  .eq(BasicPosition::getId, hxStoragePutDetailed.getPositionId())
									  .last("LIMIT 1")
									  .one();
							  orderObject.put("storehouse_id",w.getWarehouseXlbId());// 仓库id 必填
							  orderObject.put("volume", goods.getGoodsVolume());//体积
							  orderObject.put("storage_id",basicPosition.getPositionXlbId());//库位id
							  ordersArray.put(orderObject);

						  }
						  BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
								  .eq(BasicPutgoods::getId, hxStoragePutResult.getSetUnitId())
								  .one();
						  JSONObject json = new JSONObject();
						  json.put("order_fid", hxStoragePutResult.getStorageNumber());//门店申请单
//						BasicPutgoods basicPutgoods1 = basicPutgoodsService.lambdaQuery()
//								.eq(BasicPutgoods::getXlbClientId, hxOrderPutResult.getSetUnitId())
//								.one();
						  json.put("client_id",basicPutgoods.getXlbClientId());//客户id
//						json.put("client_name", "");//客户名称
						  json.put("details", ordersArray);//明细
//						json.put("memo","" );//备注
//			            json.put("return_check_fid","" );//退货质检单单号
//						json.put("return_reason","" );//退货质检原因

						  json.put("store_id",r.getStoreIdXlb());
						  json.put("storehouse_id", w.getWarehouseXlbId());
						  json.put("fid", hxStoragePutResult.getStorageNumber());//门店申请单
						  json.put("wms_fid", hxOrderPutResult.getOrderPutNumber());
					      json.put("operator", user.getName());//操作人

						//System.out.println(ordersArray);
						  //System.out.println(json);
						  //System.out.println(json);
						  //System.out.println(json);
						  //System.out.println(json);


						  BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
						  oauth2tokenParam.setDeliverId(r.getDeliverId());
						  oauth2tokenParam.setGsnumber(r.getGsnumber());
						  BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

						  String response = HttpRequest.post(url)
								  .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
								  .body(json.toString()).execute().body();

						  JSONObject jsonObject = new JSONObject(response);

						  if (jsonObject.get("code").toString().equals("0")) {
							  hxOrderPutService.lambdaUpdate()
									  .set(HxOrderPut::getReturnStatus,"已完成")
									  .eq(HxOrderPut::getOrderPutNumber,hxOrderPutResult.getOrderPutNumber())
									  .update();
							  Object data = jsonObject.get("data");
							  //System.out.println(jsonObject.toString());
							  return ResponseData.success("回传成功");
						  } else {
							  //System.out.println(jsonObject.toString());
							  TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
							  return ResponseData.error("回传失败");
						  }
		                }
				}
    		}



		}
		return ResponseData.success();
	}


	@Override
	@Transactional(rollbackFor = Exception.class,timeout=600)
	public ResponseData addGoods(User user, HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		QueryWrapper<HxStoragePut> queryWrapper = new QueryWrapper<HxStoragePut>();
		queryWrapper.eq("storage_number", hxStoragePutDetailedParam.getStorageNumber());
		HxStoragePut hxStoragePut = hxStoragePutService.getOne(queryWrapper);
		if(!hxStoragePut.getStorageState().equals("未完成")) {
			return ResponseData.error("已完成收货，无法添加");
		}
		
		String trayCode = getOperateIdOrderPrefix(user)+"-";
		
		HxOrderPutDetailedParam hxOrderPutDetailedParam = new HxOrderPutDetailedParam();
		hxOrderPutDetailedParam.setOrderPutNumber(hxStoragePutDetailedParam.getStorageNumber());
		hxOrderPutDetailedParam.setGoodsId(hxStoragePutDetailedParam.getGoodsId());
		HxOrderPutDetailedResult putD = hxOrderPutDetailedService.findBySpec(hxOrderPutDetailedParam);
		
		BigDecimal detailedPutnum = new BigDecimal(hxStoragePutDetailedParam.getNum());//入库数量
		BigDecimal Supportvolume = new BigDecimal(putD.getGoodsSupportvolume());//每托存量
		BigDecimal w = new BigDecimal(putD.getGoodsWeight());//重量
		BigDecimal v = new BigDecimal(putD.getGoodsVolume());//体积
		BigDecimal u = new BigDecimal(putD.getGoodsPrice());//单价
		int zz = 1;
		BigDecimal as = new BigDecimal(0);
		
		if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1) {//判断一托是否可以装下全部
			HxStoragePutDetailedParam s = new HxStoragePutDetailedParam();
			create(s,putD);
			s.setPutWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			s.setPutVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
			s.setPutMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			s.setStorageNumber(putD.getOrderPutNumber());
			s.setNum(hxStoragePutDetailedParam.getNum());
			BigDecimal jibenNum = new BigDecimal(hxStoragePutDetailedParam.getNum()).multiply(new BigDecimal(putD.getRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			s.setJibenNum(jibenNum.toString());
			s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);
			zz++;
			this.add(s);//添加入库单明细
		} else {
			List<HxStoragePutDetailedParam> sList = new ArrayList<HxStoragePutDetailedParam>();
			HxStoragePutDetailedParam s = new HxStoragePutDetailedParam();
			while (detailedPutnum.compareTo(as)==1) {
				if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1||detailedPutnum.subtract(Supportvolume).compareTo(as)== 0) {
					create(s,putD);
					//剩余刚好一托 够装下
					s.setPutWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					s.setPutVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
					s.setPutMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					s.setStorageNumber(putD.getOrderPutNumber());
					s.setNum(detailedPutnum.toString());
					BigDecimal jibenNum = new BigDecimal(detailedPutnum.toString()).multiply(new BigDecimal(putD.getRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					s.setJibenNum(jibenNum.toString());
					s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);
					zz++;
					detailedPutnum = new BigDecimal(0);
				} else {
					create(s,putD);
					//整托
					s.setPutWeight(w.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					s.setPutVolume(v.multiply(Supportvolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
					s.setPutMoney(u.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					s.setStorageNumber(putD.getOrderPutNumber());
					s.setNum(Supportvolume.toString());
					BigDecimal jibenNum = new BigDecimal(Supportvolume.toString()).multiply(new BigDecimal(putD.getRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					s.setJibenNum(jibenNum.toString());
					s.setTrayNumber(trayCode+DateUtil.getRandomNumber()+zz);
					zz++;
					BigDecimal detailedPutnum2	=  detailedPutnum.subtract(Supportvolume);
					detailedPutnum = detailedPutnum2;
				}
				sList.add(s);
				s = new HxStoragePutDetailedParam();
			}
			if (sList.size()>0) {
				//批量保存入库单名 ，托盘
                this.saveBatchList(sList);
			}
		}
		return ResponseData.success();
	}

	@Override
	public List<HxStoragePutDetailedResult> findAppDailingquBySpec(HxStoragePutDetailedParam hxStoragePutDetailedParam,
			String condition) {
		return this.baseMapper.findAppDailingquBySpec(hxStoragePutDetailedParam,condition);
	}

	@Override
	public List<HxStoragePutDetailedResult> findShelvesData(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		return this.baseMapper.findShelvesData(hxStoragePutDetailedParam);
	}

	@Override
	public Integer findyituijianDetailed(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		return this.baseMapper.findyituijianDetailed(hxStoragePutDetailedParam);
	}
}
